#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

static const char* SEP = " ";

class MyShell
{
    const static int NUM = 100;

    std::string USER()
    {
        const char *ret = getenv("USER");
        if (ret)
            return ret;
        return "";
    }

    std::string HOSTNAME()
    {
        const char *ret = getenv("HOSTNAME");
        if (ret)
            return ret;
        return "";
    }

    std::string PWD()
    {
        const char *ret = getenv("PWD");
        if (ret == nullptr)
            return "";
        const char *host = getenv("HOME");
        int len = strlen(host);
        if (strncmp(host, ret, len) == 0)
        {
            return "~" + std::string(ret).substr(len);
        }
        else
        {
            return host;
        }
    }
    void WriteCode(int n)
    {
        code = n;
    }
public:
    MyShell()
    {
        memset(pwd, 0, sizeof pwd);
        memset(env, 0, sizeof env);
    }
    void Interactive()
    {
        // 1. 打印命令栏
        std::cout << USER() << "@" << HOSTNAME() << ":" << PWD() << (USER() == "root" ? '#' : '$');

        // 2.获取用户输入
        std::getline(std::cin, inbuffer);
        // std::cout << inbuffer.size() << "   " <<inbuffer << std::endl;
    }
    void Split()
    {
        // 3. 分割字符串
        int i = 0;
        argv[i++] = strtok((char*)inbuffer.c_str(), SEP);
        while(argv[i++] = strtok(nullptr, SEP))
            ;
        argv[i] = NULL;
    }

    int BuildinCMD()
    {
        if(strcmp("cd", argv[0]) == 0)
        {
            if(argv[1])
            {
                std::string newPath = argv[1];
                auto pos = newPath.find('~');
                if(pos != std::string::npos)
                {
                    newPath.replace(pos, 1, getenv("HOME"));
                }

                chdir(newPath.c_str());
                char tmp[1024];
                getcwd(tmp, 1024);
                snprintf(pwd, sizeof(pwd), "PWD=%s", tmp);
                putenv(pwd);
            }
            WriteCode(0);   
            return 1;
        }
        else if(strcmp("export", argv[0]) == 0)
        {
            if(argv[1])
            {
                strcpy(env, argv[1]);
                putenv(env);
            }
            WriteCode(0);   
            return 1;
        }
        else if(strcmp("env", argv[0]) == 0)
        {
            extern char** environ;
            for (int i = 0; environ[i] ; i++)
                std::cout << environ[i] << std::endl;
            WriteCode(0);   
            return 1;
        }
        else if(strcmp("echo", argv[0]) == 0)
        {
            if(argv[1] == NULL)
            {
                std::cout << std::endl;
            }
            else
            {
                std::string s = argv[1];
                if(s.size() > 0 && s[0] == '$')
                {
                    if(s.size() > 1 && s[1] == '?')
                    {
                        std::cout << code << std::endl;
                    }
                    else
                    {
                        const char* ret = getenv(argv[1] + 1);
                        if(ret)
                            std::cout << ret << std::endl;
                        std::cout << std::endl;
                    }
                }
                else
                {
                    std::cout << argv[1] << std::endl;
                }
            }
            WriteCode(0);   
            return 1;
        }        
        return 0;
    }
    void Excute()
    {
        // 4. 程序替换
        pid_t id = fork();
        if(id == 0)
        {
            execvp(argv[0], argv);
            exit(1);
        }
        int status;
        int n = waitpid(id, &status, 0);
        if(WIFEXITED(status))
        {
            std::cout << "exit code : " << WEXITSTATUS(status) << std::endl;
        }
        else
        {
            std::cout << "error" << std::endl;
        }
        code = WEXITSTATUS(status);
    }
    bool empty() const
    {
        return inbuffer.empty();
    }
private:
    std::string inbuffer;
    char* argv[NUM];

    int code = 0; //退出码

    char pwd[1024];
    char env[1024];

};

int main()
{
    MyShell ms;
    while (1)
    {
        ms.Interactive();
        if(ms.empty())
            continue;
        ms.Split();
        int n = ms.BuildinCMD();
        if(n)
            continue;
        ms.Excute();
    }
    return 0;
}